package com.fy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fy.common.constants.MessageConstant;
import com.fy.ex.ConditionException;
import com.fy.mapper.AdminSysMapper;
import com.fy.mapper.FileInfoMapper;
import com.fy.mapper.UserMapper;
import com.fy.pojo.dto.file.FileQueryDTO;
import com.fy.pojo.entity.AdminSys;
import com.fy.pojo.entity.FileInfo;
import com.fy.pojo.entity.User;
import com.fy.pojo.enums.FileDelFlagEnums;
import com.fy.pojo.enums.FileFolderTypeEnums;
import com.fy.pojo.vo.admin.AdminSysVO;
import com.fy.pojo.vo.file.PageResultData;
import com.fy.service.AdminService;
import com.fy.utils.DateFormatter;
import com.fy.utils.result.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminSysMapper adminSysMapper;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    /**
     * 启用禁用用户账号
     *
     * @param userId
     * @param status
     */
    @Override
    public void updateUserStatus(String userId, String status) {
        userMapper.updateStatusById(Integer.parseInt(userId), Integer.parseInt(status));
    }

    /**
     * 分配用户空间
     * @param nickName
     * @param totalSpace
     * @param useSpace
     * @param changeSpace
     */

    @Override
    public void updateUserSpace(String nickName, long totalSpace, long useSpace, long changeSpace) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, nickName);
        User user = userMapper.selectOne(queryWrapper);
        log.info("user:{}", user);
        // 判断帐号状态
        if (user.getStatus() == 0) {
            throw new ConditionException("账户禁用状态, 无法分配空间!");
        }

        // 判断空间情况
        if (useSpace > changeSpace) {
            throw new ConditionException(MessageConstant.LOW_SPACE_ERROR);
        }

        userMapper.updateTotalSpaceByName(nickName, changeSpace);
    }

    /**
     * 获取用户文件列表
     *
     * @param fileQueryDTO
     * @return
     */
    @Override
    public PageResult loadFileList(FileQueryDTO fileQueryDTO) {

        long pageSize = fileQueryDTO.getPageSize() != null && !fileQueryDTO.getPageSize().isEmpty()
                ? Long.parseLong(fileQueryDTO.getPageSize())
                : 15L;
        long pageNo = fileQueryDTO.getPageNo() != null && !fileQueryDTO.getPageNo().isEmpty()
                ? Long.parseLong(fileQueryDTO.getPageNo())
                : 1L;

        String filePid = fileQueryDTO.getFilePid();
        if (filePid == null || filePid.isEmpty()) {
            filePid = " ";
        }

        String fileNameFuzzy = fileQueryDTO.getFileNameFuzzy() != null ? fileQueryDTO.getFileNameFuzzy() : null;

        IPage<FileInfo> page = new Page<>(pageNo, pageSize);
        // 构建查询条件
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_type", FileDelFlagEnums.USING.getFlag());

        // 判断关键字查询条件
        if (StringUtils.isNotBlank(fileNameFuzzy)) {
            queryWrapper.like("file_name", fileNameFuzzy.toLowerCase()); // 将关键字转换为小写
        }
        // 看看是不是文件夹的文件
        if (filePid != " ") {
            queryWrapper.eq("file_pid", filePid);
        }

        //只获取文件，不要文件夹
        queryWrapper.eq("folder_type", FileFolderTypeEnums.FILE.getType());

        fileInfoMapper.selectPage(page, queryWrapper);

        List<FileInfo> list1 = page.getRecords();
        List<PageResultData> list2 = list1.stream()
                .map(record -> {
                    PageResultData pageResultData = new PageResultData();
                    BeanUtils.copyProperties(record, pageResultData);

                    // 格式化 createTime 和 lastUpdateTime
                    if (record.getCreateTime() != null) {
                        pageResultData.setRecoveryTime(
                                DateFormatter.getYMDhmsFormatterStringByCST(String.valueOf(record.getCreateTime())));
                    }
                    if (record.getLastUpdateTime() != null) {
                        pageResultData.setLastUpdateTime(DateFormatter
                                .getYMDhmsFormatterStringByCST(String.valueOf(record.getLastUpdateTime())));
                    }

                    return pageResultData;
                })
                .collect(Collectors.toList());

        PageResult pageResult = new PageResult();
        pageResult.setTotalCount(page.getTotal());
        pageResult.setPageNo(page.getCurrent());
        pageResult.setPageSize(page.getSize());
        pageResult.setPageTotal(page.getPages());
        pageResult.setList(list2);

        log.info("一共多少页: {}", page.getPages());
        log.info("当前页码: {}", page.getCurrent());
        log.info("每页显示数: {}", page.getSize());
        log.info("一共多少条数据: {}", page.getTotal());

        return pageResult;

    }

    /**
     * 获取系统设置
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = { SQLException.class, RuntimeException.class })
    public AdminSysVO getSysSettings() {
        AdminSys adminSys = adminSysMapper.selectOne(null);
        AdminSysVO adminSysVO = new AdminSysVO();
        adminSysVO.setUserInitUseSpace(String.valueOf(adminSys.getUserInitUseSpace()));
        adminSysVO.setRegisterEmailContent(String.valueOf(adminSys.getPicCodeOutTime()));
        adminSysVO.setRegisterEmailTitle(String.valueOf(adminSys.getEmCodeOutTime()));
        return adminSysVO;
    }

    /**
     * 保存系统设置
     *
     * @param adminSys
     */
    @Override
    public void saveSysSettings(AdminSys adminSys) {
        adminSysMapper.update(adminSys, null);
    }

    /**
     * 文件删除
     *
     * @param fileIdList
     */
    @Override
    public void delFile(List<String> fileIdList) {
        // 获取删除进入回收站时间
        LocalDateTime now = LocalDateTime.now();
        // 将 LocalDateTime 转换为 Date
        Date nowAsDate = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        for (String fileId : fileIdList) {
            String[] parts = fileId.split("_");
            String result = parts[1];
            fileInfoMapper.updateDelFlagByFileId(result, FileDelFlagEnums.RECYCLE.getFlag(), nowAsDate);
        }
    }
}
